﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.ProductionOrders;
using SmartProduction.Domain.Ptoduction;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.SCWorkCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.SCWorkCommandHandler
{
    public class SCDanHaoQuerycommandHandler : IRequestHandler<SCDanHaoQuerycommand, APIPaing<List<AssociatedProductionOrder>>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 上产单号仓储接口
        /// </summary>
        private readonly IBaseRepository<AssociatedProductionOrder> aRepo;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="aRepo"></param>
        public SCDanHaoQuerycommandHandler(IMapper mapper, IBaseRepository<AssociatedProductionOrder> aRepo)
        {
            this.mapper = mapper;
            this.aRepo = aRepo;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaing<List<AssociatedProductionOrder>>> Handle(SCDanHaoQuerycommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIPaing<List<AssociatedProductionOrder>> result = new APIPaing<List<AssociatedProductionOrder>>();
                var list = aRepo.GetAll().Result;
                result.TotalCount = list.Count();
                result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
                list = list.OrderByDescending(o => o.AssociatedProductionOrderId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                var data = mapper.Map<List<AssociatedProductionOrder>>(list);
                result.Code = APIEnums.查询成功;
                result.Msg = APIEnums.查询成功.ToString();
                result.data = data;
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
